package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.bellettini.BellettiniProductResDTO;
import com.atmilan.quartz.model.dto.carotta.CarottaProductResDTO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class CarrottaProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;
    @Value("${carotta.url}")
    private String carottaUrl;
    @Value("${carotta.key}")
    private String carottaKey;
    @Value("${carotta.password}")
    private String carottaPassword;
    @Value("${carotta.version}")
    private String carottaVersion;

    /**
     * 获取Carotta产品列表
     * @return
     */
    public CarottaProductResDTO getCarottaProducts(Integer pageSize, String pageInfo) throws JsonProcessingException {
        CarottaProductResDTO carottaProductResDTO = null;
        try {
            StringBuilder sb = new StringBuilder().append("https://")
                    .append(carottaKey)
                    .append(":")
                    .append(carottaPassword)
                    .append("@")
                    .append(carottaUrl)
                    .append("/admin/api/")
                    .append(carottaVersion)
                    .append("/products.json")
                    .append("?limit=")
                    .append(pageSize);
            if(StringUtils.isNotBlank(pageInfo)){
                sb.append("&page_info=").append(pageInfo);
            }
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- 获取Carotta产品列表异常{} ---------------", errorMessage);
            }
            List<String> link = response.getHeaders().get("Link");
            String str = null;
            if(CollectionUtils.isNotEmpty(link)){
                str = link.stream().map(e -> {
                    if (e.contains("rel=\"next\"")) {
                        String info = StringUtils.substringBetween(e, "page_info=", ">; rel=\"next\"");
                        if(info.contains("page_info=")){
                            info = StringUtils.substringAfter(info, "page_info=");
                        }
                        return info;
                    }
                    return null;
                }).collect(Collectors.joining());
            }
            ObjectMapper mapper = new ObjectMapper();
            carottaProductResDTO = mapper.readValue(response.getBody(), CarottaProductResDTO.class);
            carottaProductResDTO.setPageInfo(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return carottaProductResDTO;
    }

    /**
     * 获取商品总数
     * @return
     */
    public Integer getCarottaCount() {
        try {
            StringBuilder sb = new StringBuilder().append("https://")
                    .append(carottaKey)
                    .append(":")
                    .append(carottaPassword)
                    .append("@")
                    .append(carottaUrl)
                    .append("/admin/api/")
                    .append(carottaVersion)
                    .append("/products/count.json");
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- Carotta获取商品总数异常{} ---------------", errorMessage);
            }
            return (Integer) JSONObject.parseObject(response.getBody()).get("count");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
